<template>
  <view class="next-tree">
    <view
      class="next-tree-mask"
      :class="showTree ? 'show' : ''"
      @tap="_cancel"
    ></view>
    <view class="next-tree-cnt" :class="showTree ? 'show' : ''">
      <view class="next-tree-bar">
        <view
          class="next-tree-bar-cancel"
          :style="{ color: cancelColor }"
          hover-class="hover-c"
          @tap="_cancel"
          >取消</view
        >
        <view class="next-tree-bar-title" :style="{ color: titleColor }">{{
          title
        }}</view>
        <view
          class="next-tree-bar-confirm"
          :style="{ color: confirmColor }"
          hover-class="hover-c"
          @tap="_confirm"
          >确定</view
        >
      </view>
      <view class="next-tree-view">
        <scroll-view class="next-tree-view-sc" :scroll-y="true">
          <block v-for="(item, index) in treeList" :key="index">
            <view
              class="next-tree-item"
              :style="[
                {
                  paddingLeft: item.rank * 15 + 'px',
                  zIndex: item.rank * -1 + 50
                }
              ]"
              :class="{
                border: border === true,
                show: item.show,
                last: item.lastRank,
                showchild: item.showChild,
                open: item.open
              }"
            >
              <view
                class="next-tree-label"
                @tap.stop="_treeItemTap(item, index)"
              >
                <image
                  class="next-tree-icon"
                  :src="
                    item.lastRank
                      ? lastIcon
                      : item.showChild
                      ? currentIcon
                      : defaultIcon
                  "
                ></image>
                {{ item.name }}
              </view>
              <view
                class="next-tree-check"
                @tap.stop="_treeItemSelect(item, index)"
                v-if="selectParent ? true : item.lastRank"
              >
                <view
                  class="next-tree-check-yes"
                  v-if="item.checked"
                  :class="{ radio: !multiple }"
                  :style="{
                    'border-color': confirmColor,
                    'background-color': confirmColor
                  }"
                >
                  <view
                    class="next-tree-check-yes-b"
                    :style="{ 'background-color': confirmColor }"
                  >
                    <!-- <text class="icon-text">✔</text> -->
                    <u-icon name="checkmark" color="#ffffff"></u-icon>
                  </view>
                </view>
                <view
                  class="next-tree-check-no"
                  v-else
                  :class="{ radio: !multiple }"
                  :style="{ 'border-color': confirmColor }"
                ></view>
              </view>
            </view>
          </block>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "next-tree",
  props: {
    treeData: {
      type: Array,
      default: function () {
        return [];
      },
    },
    valueKey: {
      type: String,
      default: "id",
    },
    labelKey: {
      type: String,
      default: "label",
    },
    childrenKey: {
      type: String,
      default: "children",
    },
    title: {
      type: String,
      default: "",
    },
    multiple: {
      // 是否可以多选
      type: Boolean,
      default: false,
    },
    selectParent: {
      //是否可以选父级
      type: Boolean,
      default: false,
    },
    foldAll: {
      //折叠时关闭所有已经打开的子集，再次打开时需要一级一级打开
      type: Boolean,
      default: false,
    },
    confirmColor: {
      // 确定按钮颜色
      type: String,
      default: "#00443A", // #f9ae3d
    },
    cancelColor: {
      // 取消按钮颜色
      type: String,
      default: "", // #757575
    },
    titleColor: {
      // 标题颜色
      type: String,
      default: "", // #757575
    },
    currentIcon: {
      // 展开时候的ic
      type: String,
      default:
        "",
    },
    defaultIcon: {
      // 折叠时候的ic
      type: String,
      default:
        "",
    },
    lastIcon: {
      // 没有子集的ic
      type: String,
      default: "",
    },
    border: {
      // 是否有分割线
      type: Boolean,
      default: false,
    },
  },
  data () {
    return {
      showTree: false,
      treeList: [],
      selectIndex: -1,
      childNums: [],
      rt: [],
      rtName: [],
    };
  },
  computed: {},
  methods: {
    _show () {
      this.showTree = true;
    },
    _hide () {
      this.showTree = false;
    },
    _cancel () {
      this._hide();
      this.$emit("cancel", "");
      console.log(this.showTree);
    },
    _confirm () {
      this.rt = [];
      this.rtName = [];
      // 处理所选数据
      this.treeList.forEach((item, i) => {
        if (item.id == 100 && item.checked) {
          return this.confirmEach(this.treeData);
        }
        if (item.checked && item.parentId && item.parentId != "100") {
          this.rt.push(item.id);
          this.rtName.push(item.name);
        }
      });
      this._hide();
      this.$emit("confirm", { id: this.rt, name: this.rtName });
    },
    confirmEach (list) {
      list.forEach((item, index) => {
        if (item.isDy) {
          this.rtName.push(item.name);
          this.rt.push(item.id);
        }
        if (item.children && item.children.length > 0)
          this.confirmEach(item.children);
      });
    },
    //扁平化树结构
    _renderTreeList (list = [], rank = 0, parentId = [], parents = []) {
      list.forEach((item) => {
        this.treeList.push({
          id: item[this.valueKey],
          name: item[this.labelKey],
          source: item,
          parentId, // 父级id数组
          parents, // 父级id数组
          rank, // 层级
          showChild: true, //子级是否显示
          open: true, //是否打开
          show: true, // 自身是否显示
          hideArr: [],
          orChecked: item.checked ? item.checked : false,
          checked: item.checked ? item.checked : false,
        });
        if (
          Array.isArray(item[this.childrenKey]) &&
          item[this.childrenKey].length > 0
        ) {
          // console.log(item)
          let parentid = [...parentId],
            parentArr = [...parents],
            childrenid = [];
          delete parentArr.children;
          parentid.push(item[this.valueKey]);
          parentArr.push({
            [this.valueKey]: item[this.valueKey],
            [this.labelKey]: item[this.labelKey],
          });
          this._renderTreeList(
            item[this.childrenKey],
            rank + 1,
            parentid,
            parentArr
          );
        } else {
          this.treeList[this.treeList.length - 1].lastRank = true;
        }
      });
    },
    // 处理默认选择
    _defaultSelect () {
      this.treeList.forEach((v, i) => {
        if (v.checked) {
          this.treeList.forEach((v2, i2) => {
            if (v.parentId.toString().indexOf(v2.parentId.toString()) >= 0) {
              v2.show = true;
              if (v.parentId.includes(v2.id)) {
                v2.showChild = true;
                v2.open = true;
              }
            }
          });
        }
      });
      this._confirm();
    },
    // 点击
    _treeItemTap (item, index) {
      if (item.lastRank === true) {
        //点击最后一级时触发事件
        this.treeList[index].checked = !this.treeList[index].checked;
        this._fixMultiple(index);
        return;
      }
      let list = this.treeList;
      let id = item.id;
      item.showChild = !item.showChild;
      item.open = item.showChild ? true : !item.open;
      list.forEach((childItem, i) => {
        if (item.showChild === false) {
          //隐藏所有子级
          if (!childItem.parentId.includes(id)) {
            return;
          }
          if (!this.foldAll) {
            if (childItem.lastRank !== true && !childItem.open) {
              childItem.showChild = false;
            }
            // 为隐藏的内容添加一个标记
            if (childItem.show) {
              childItem.hideArr[item.rank] = id;
            }
          } else {
            if (childItem.lastRank !== true) {
              childItem.showChild = false;
            }
          }
          childItem.show = false;
        } else {
          // 打开子集
          if (childItem.parentId[childItem.parentId.length - 1] === id) {
            childItem.show = true;
          }
          // 打开被隐藏的子集
          if (childItem.parentId.includes(id) && !this.foldAll) {
            // console.log(childItem.hideArr)
            if (childItem.hideArr[item.rank] === id) {
              childItem.show = true;
              if (childItem.open && childItem.showChild) {
                childItem.showChild = true;
              } else {
                childItem.showChild = false;
              }
              childItem.hideArr[item.rank] = null;
            }
          }
        }
      });
    },
    _treeItemSelect (item, index) {
      this.treeList[index].checked = !this.treeList[index].checked;
      // 选父级, 子级自动全选
      this.syncChecked(this.treeList, item.id, this.treeList[index].checked);
      if (item.rank > 0) {
        item.parentId.forEach((pid, indexP) => {
          const parent = this.treeList.filter((i) => i.id === pid);
          const childNum = parent.length > 0 ? parent[0].childNum : 0;
          if (this.childNums[pid] === undefined) {
            this.childNums[pid] = 1;
          } else if (this.childNums[pid] < childNum) {
            this.childNums[pid]++;
          }
        });
        //子级选择/选满/取消选择, 父级往上同步状态
        this.setAncestors(item.parentId, this.treeList[index].checked);
      }
      this._fixMultiple(index);
    },
    syncChecked (trees, pid, checked) {
      trees.forEach((item, index) => {
        if (item.parentId.includes(pid)) {
          this.treeList[index].checked = checked;
          this.syncChecked(trees, item.id, checked);
        } else if (item.children !== undefined) {
          this.syncChecked(item.children, pid, checked);
        }
      });
    },
    setAncestors (pids, checked) {
      this.treeList.forEach((item, index) => {
        if (pids.includes(item.id)) {
          if (
            checked &&
            this.childNums[item.id] !== undefined &&
            item.childNum === this.childNums[item.id]
          ) {
            // 子级全部选中, 父级才选中
            this.treeList[index].checked = true;
          } else {
            this.treeList[index].checked = false;
          }
          this.setAncestors(item.parentId, checked);
        }
      });
    },
    // _treeItemSelect(item, index) {
    // 	this.treeList[index].checked = !this.treeList[index].checked
    // 	this._fixMultiple(index)
    // },
    // 处理单选多选
    _fixMultiple (index) {
      if (!this.multiple) {
        // 如果是单选
        this.treeList.forEach((v, i) => {
          if (i != index) {
            this.treeList[i].checked = false;
          } else {
            this.treeList[i].checked = true;
          }
        });
      }
    },
    // 重置数据
    _reTreeList () {
      this.treeList.forEach((v, i) => {
        this.treeList[i].checked = v.orChecked;
      });
    },
    _initTree (treeData = this.treeData) {
      this.treeList = [];
      this._renderTreeList(treeData);
      this.$nextTick(() => {
        this._defaultSelect(treeData);
      });
    },
  },
  mounted () {
    // this._initTree();
    this.$watch(
      () => this.treeData,
      (list) => {
        this._initTree(list);
      },
      { deep: true, immediate: true }
    );
    this.$watch(
      () => [this.multiple, this.selectParent],
      () => {
        if (this.treeData.length) {
          this._reTreeList();
        }
      },
      { deep: true, immediate: true }
    );
  },
};
</script>

<style scoped>
.next-tree-mask {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 999998;
  background-color: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: all 0.3s ease;
  visibility: hidden;
}
.show {
  visibility: visible;
  opacity: 1;
}
.next-tree-cnt {
  position: fixed;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  z-index: 999999;
  top: 200rpx;
  transition: all 0.3s ease;
  transform: translateY(100%);
}
.show {
  transform: translateY(0);
}
.next-tree-bar {
  background-color: #fff;
  height: 72rpx;
  padding-left: 20rpx;
  padding-right: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  border-bottom-width: 1rpx !important;
  border-bottom-style: solid;
  border-bottom-color: #f5f5f5;
  font-size: 32rpx;
  color: #757575;
  line-height: 1;
}
.next-tree-bar-confirm {
  color: #f9ae3d;
}
.next-tree-view {
  position: absolute;
  top: 0rpx;
  right: 0rpx;
  bottom: 0rpx;
  left: 0rpx;
  top: 72rpx;
  background-color: #fff;
  padding-top: 20rpx;
  padding-right: 20rpx;
  padding-bottom: 20rpx;
  padding-left: 20rpx;
}
.next-tree-view-sc {
  height: 80%;
  overflow: hidden;
}
.next-tree-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 26rpx;
  color: #757575;
  line-height: 1;
  height: 0;
  opacity: 0;
  transition: 0.2s;
  position: relative;
  overflow: hidden;
}
.next-tree-item.show {
  height: 80rpx;
  opacity: 1;
}
.next-tree-item.showchild:before {
  transform: rotate(90deg);
}
.next-tree-item.border {
  border-bottom: 1rpx solid rgba(204, 204, 204, 0.2);
}
.next-tree-item.last:before {
  opacity: 0;
}
.next-tree-icon {
  width: 26rpx;
  height: 26rpx;
  margin-right: 8rpx;
}
.next-tree-label {
  flex: 1;
  display: flex;
  align-items: center;
  height: 100%;
  line-height: 1.2;
}
.next-tree-check {
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.next-tree-check-yes,
.next-tree-check-no {
  width: 20px;
  height: 20px;
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  border-top-width: 2rpx;
  border-left-width: 2rpx;
  border-bottom-width: 2rpx;
  border-right-width: 2rpx;
  border-style: solid;
  border-color: #f9ae3d;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}
.next-tree-check-yes-b {
  border-top-left-radius: 20%;
  border-top-right-radius: 20%;
  border-bottom-right-radius: 20%;
  border-bottom-left-radius: 20%;
  background-color: #f9ae3d;
  color: #fff;
}
.next-tree-check-yes-b .icon-text {
  font-size: 14px;
  font-weight: normal;
  font-family: uicon-iconfont;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.next-tree-check .radio {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}
.next-tree-check .radio .next-tree-check-yes-b {
  border-top-left-radius: 50%;
  border-top-right-radius: 50%;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}
.hover-c {
  opacity: 0.6;
}
</style>
